<template>
  <div class="file-management">
    <div class="page-header">
      <h2>文件管理</h2>
      <div class="header-actions">
        <el-button type="success" @click="handleCreateFolder">
          <el-icon><FolderAdd /></el-icon>
          新建文件夹
        </el-button>
        <el-button type="primary" @click="handleUpload">
          <el-icon><Upload /></el-icon>
          上传文件
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>文件列表</span>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文件或文件夹"
            style="width: 200px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table :data="filteredFiles" v-loading="loading">
        <el-table-column label="文件名" min-width="400">
          <template #default="{ row }">
            <div class="file-name">
              <el-icon :color="row.type === 'folder' ? '#409EFF' : '#606266'">
                <Folder v-if="row.type === 'folder'" />
                <Document v-else />
              </el-icon>
              <span class="name-text">{{ row.name }}</span>
              <el-tag v-if="row.type === 'folder'" :type="row.folderType === 'public' ? 'success' : 'warning'" size="small" style="margin-left: 8px;">
                {{ row.folderType === 'public' ? '公开' : '私有' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="uploader" label="上传者" width="120" />
        <el-table-column prop="uploadTime" label="上传时间" width="180" />
        <el-table-column prop="isPublic" label="权限" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isPublic ? 'success' : 'warning'" size="small">
              {{ row.isPublic ? '公开' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                v-if="canDownload(row)" 
                type="primary" 
                size="small" 
                @click="handleDownload(row)"
              >
                下载
              </el-button>
              <el-button 
                v-if="canManage(row)" 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
              >
                删除
              </el-button>
              <el-button 
                v-if="row.type === 'folder' && canManage(row)" 
                type="warning" 
                size="small" 
                @click="handleEditFolder(row)"
              >
                编辑
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 上传文件对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="上传文件"
      width="500px"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="文件名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="权限" prop="isPublic">
          <el-radio-group v-model="formData.isPublic">
            <el-radio :value="true">公开</el-radio>
            <el-radio :value="false">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            上传
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog
      v-model="folderDialogVisible"
      title="新建文件夹"
      width="500px"
      @close="handleFolderClose"
    >
      <el-form
        ref="folderFormRef"
        :model="folderFormData"
        :rules="folderFormRules"
        label-width="100px"
      >
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="folderFormData.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="文件夹类型" prop="folderType">
          <el-radio-group v-model="folderFormData.folderType">
            <el-radio value="public">公开文件夹</el-radio>
            <el-radio value="private">私有文件夹</el-radio>
          </el-radio-group>
          <div class="form-tip">
            <el-text type="info" size="small">
              公开文件夹：只有管理员可以上传下载<br/>
              私有文件夹：只有您自己可以管理
            </el-text>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="folderFormData.description" 
            type="textarea" 
            placeholder="请输入文件夹描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleFolderClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleFolderSubmit">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑文件夹对话框 -->
    <el-dialog
      v-model="editFolderDialogVisible"
      title="编辑文件夹"
      width="500px"
      @close="handleEditFolderClose"
    >
      <el-form
        ref="editFolderFormRef"
        :model="editFolderFormData"
        :rules="editFolderFormRules"
        label-width="100px"
      >
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="editFolderFormData.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="文件夹类型" prop="folderType">
          <el-radio-group v-model="editFolderFormData.folderType" :disabled="!isAdmin">
            <el-radio value="public">公开文件夹</el-radio>
            <el-radio value="private">私有文件夹</el-radio>
          </el-radio-group>
          <div v-if="!isAdmin" class="form-tip">
            <el-text type="warning" size="small">
              只有管理员可以修改文件夹类型
            </el-text>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editFolderFormData.description" 
            type="textarea" 
            placeholder="请输入文件夹描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleEditFolderClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleEditFolderSubmit">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Upload, Search, Document, Folder, FolderAdd } from '@element-plus/icons-vue'
import { useFileStore } from '@/stores/file'
import { useUserStore } from '@/stores/user'
import type { FileItem, FileForm } from '@/types'

const fileStore = useFileStore()
const userStore = useUserStore()

const loading = ref(false)
const dialogVisible = ref(false)
const folderDialogVisible = ref(false)
const editFolderDialogVisible = ref(false)
const searchKeyword = ref('')
const formRef = ref<FormInstance>()
const folderFormRef = ref<FormInstance>()
const editFolderFormRef = ref<FormInstance>()
const editingFolderId = ref<number | null>(null)

const files = ref<FileItem[]>([])

const formData = reactive<FileForm>({
  name: '',
  type: 'folder',
  parentId: undefined,
  description: '',
  tags: [],
  category: 'other',
  isPublic: true
})

const folderFormData = reactive<FileForm>({
  name: '',
  type: 'folder',
  parentId: undefined,
  description: '',
  tags: [],
  category: 'other',
  isPublic: true,
  folderType: 'private',
  ownerId: userStore.user?.id
})

const editFolderFormData = reactive<FileForm>({
  name: '',
  type: 'folder',
  parentId: undefined,
  description: '',
  tags: [],
  category: 'other',
  isPublic: true,
  folderType: 'private',
  ownerId: userStore.user?.id
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入文件名', trigger: 'blur' }
  ]
}

const folderFormRules: FormRules = {
  name: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' }
  ],
  folderType: [
    { required: true, message: '请选择文件夹类型', trigger: 'change' }
  ]
}

const editFolderFormRules: FormRules = {
  name: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' }
  ],
  folderType: [
    { required: true, message: '请选择文件夹类型', trigger: 'change' }
  ]
}

// 过滤后的文件列表
const filteredFiles = computed(() => {
  if (!searchKeyword.value) {
    return files.value
  }
  return files.value.filter(file =>
    file.name.includes(searchKeyword.value)
  )
})

// 检查是否为管理员
const isAdmin = computed(() => {
  return userStore.user?.roles.includes('admin') || false
})

// 权限检查方法
const canDownload = (file: FileItem) => {
  if (file.type === 'folder') {
    return fileStore.checkFolderPermission(file.id, 'download')
  } else {
    return fileStore.checkFilePermission(file.id, 'download')
  }
}

const canManage = (file: FileItem) => {
  if (file.type === 'folder') {
    return fileStore.checkFolderPermission(file.id, 'manage')
  } else {
    return fileStore.checkFilePermission(file.id, 'delete')
  }
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size === 0) return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  let fileSize = size
  
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  
  return `${fileSize.toFixed(1)} ${units[index]}`
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    files.value = await fileStore.getAllFiles()
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑在computed中处理
}

// 双击行
const handleRowDoubleClick = (row: FileItem) => {
  // 简化版本，暂时不做文件夹导航
}

// 上传文件
const handleUpload = () => {
  resetForm()
  dialogVisible.value = true
}

// 新建文件夹
const handleCreateFolder = () => {
  resetFolderForm()
  folderDialogVisible.value = true
}

// 编辑文件夹
const handleEditFolder = (folder: FileItem) => {
  editingFolderId.value = folder.id
  Object.assign(editFolderFormData, {
    name: folder.name,
    type: 'folder',
    parentId: folder.parentId,
    description: folder.description || '',
    tags: folder.tags,
    category: folder.category,
    isPublic: folder.isPublic,
    folderType: folder.folderType || 'private',
    ownerId: folder.ownerId
  })
  editFolderDialogVisible.value = true
}

// 下载
const handleDownload = async (row: FileItem) => {
  try {
    await fileStore.incrementDownloadCount(row.id)
    ElMessage.success('开始下载...')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 删除
const handleDelete = async (row: FileItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await fileStore.deleteFile(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    await fileStore.createFile(formData)
    ElMessage.success('创建成功')
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    type: 'file',
    parentId: undefined,
    description: '',
    tags: [],
    category: 'other',
    isPublic: true
  })
  formRef.value?.resetFields()
}

// 重置文件夹表单
const resetFolderForm = () => {
  Object.assign(folderFormData, {
    name: '',
    type: 'folder',
    parentId: undefined,
    description: '',
    tags: [],
    category: 'other',
    isPublic: true,
    folderType: 'private',
    ownerId: userStore.user?.id
  })
  folderFormRef.value?.resetFields()
}

// 重置编辑文件夹表单
const resetEditFolderForm = () => {
  Object.assign(editFolderFormData, {
    name: '',
    type: 'folder',
    parentId: undefined,
    description: '',
    tags: [],
    category: 'other',
    isPublic: true,
    folderType: 'private',
    ownerId: userStore.user?.id
  })
  editFolderFormRef.value?.resetFields()
  editingFolderId.value = null
}

// 提交文件夹表单
const handleFolderSubmit = async () => {
  if (!folderFormRef.value) return
  
  try {
    await folderFormRef.value.validate()
    
    await fileStore.createFile(folderFormData)
    ElMessage.success('文件夹创建成功')
    
    folderDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

// 提交编辑文件夹表单
const handleEditFolderSubmit = async () => {
  if (!editFolderFormRef.value || !editingFolderId.value) return
  
  try {
    await editFolderFormRef.value.validate()
    
    await fileStore.updateFile(editingFolderId.value, editFolderFormData)
    ElMessage.success('文件夹更新成功')
    
    editFolderDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 关闭文件夹对话框
const handleFolderClose = () => {
  folderDialogVisible.value = false
  resetFolderForm()
}

// 关闭编辑文件夹对话框
const handleEditFolderClose = () => {
  editFolderDialogVisible.value = false
  resetEditFolderForm()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.file-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
    }
    
    .file-name {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .name-text {
        font-weight: 500;
      }
    }
  }
  
  .form-tip {
    margin-top: 8px;
    line-height: 1.4;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
